package xx.iverson.listening_manager.service.impl;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import xx.iverson.listening_manager.entity.AudioFile;
import xx.iverson.listening_manager.mapper.AudioFileMapper;
import xx.iverson.listening_manager.result.ReturnResult;
import xx.iverson.listening_manager.service.AudioFileService;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * xx.iverson.listening_manager.service.impl.AudioFileServiceImpl
 * 描述：
 * on 2025/10/17-上午9:04
 *
 * @author weijx
 */

@Service
public class AudioFileServiceImpl implements AudioFileService {

    @Resource
    private AudioFileMapper audioFileMapper;

    @Value("${file.upload-dir:uploads}")
    private String uploadDir;

    // 允许的音频文件类型
    private static final List<String> ALLOWED_FILE_TYPES = Arrays.asList(
            "audio/mpeg", "audio/mp3", "audio/wav", "audio/ogg"
    );

    // 最大文件大小 100MB
    private static final long MAX_FILE_SIZE = 100 * 1024 * 1024;

    @Override
    public ReturnResult<List<AudioFile>> getAllAudioFiles() {
        try {
            List<AudioFile> audioFiles = audioFileMapper.selectAllAudioFiles();
            return ReturnResult.success(audioFiles);
        } catch (Exception e) {
            return ReturnResult.error(500, "获取听力文件列表失败");
        }
    }

    @Override
    public ReturnResult<AudioFile> getAudioById(Integer audioId) {
        try {
            AudioFile audioFile = audioFileMapper.selectAudioById(audioId);
            if (audioFile == null) {
                return ReturnResult.notFound();
            }
            return ReturnResult.success(audioFile);
        } catch (Exception e) {
            return ReturnResult.error(500, "获取听力文件失败");
        }
    }

    @Override
    public ReturnResult<List<AudioFile>> getAudioByLevel2CategoryId(Integer categoryId) {
        try {
            List<AudioFile> audioFiles = audioFileMapper.selectAudioByLevel2CategoryId(categoryId);
            return ReturnResult.success(audioFiles);
        } catch (Exception e) {
            return ReturnResult.error(500, "获取分类听力文件失败");
        }
    }

    @Override
    public ReturnResult<List<AudioFile>> getAudioByLevel1CategoryId(Integer categoryId) {
        try {
            List<AudioFile> audioFiles = audioFileMapper.selectAudioByLevel1CategoryId(categoryId);
            return ReturnResult.success(audioFiles);
        } catch (Exception e) {
            return ReturnResult.error(500, "获取分类听力文件失败");
        }
    }

    @Override
    public ReturnResult<AudioFile> uploadAudio(MultipartFile file, AudioFile audioFile) {
        File destFile = null;
        try {
            // 验证文件
            if (file.isEmpty()) {
                return ReturnResult.error(400, "文件不能为空");
            }

            if (file.getSize() > MAX_FILE_SIZE) {
                return ReturnResult.error(400, "文件大小不能超过100MB");
            }

            if (!ALLOWED_FILE_TYPES.contains(file.getContentType())) {
                return ReturnResult.error(400, "只支持MP3、WAV、OGG格式的音频文件");
            }

            // 生成存储路径
            String storagePath = generateStoragePath(file.getOriginalFilename());
            destFile = new File(uploadDir + File.separator + storagePath);

            // 创建目录
            destFile.getParentFile().mkdirs();

            // 保存文件
            file.transferTo(destFile);

            // 设置文件信息
            audioFile.setOriginalFilename(file.getOriginalFilename());
            audioFile.setStoragePath(storagePath);
            audioFile.setFileSize(file.getSize());
            audioFile.setFileFormat(getFileExtension(file.getOriginalFilename()));
            audioFile.setDuration(0);

            // 插入数据库
            int result = audioFileMapper.insertAudio(audioFile);
            if (result > 0) {
                // 返回包含ID的完整信息
                AudioFile savedAudio = audioFileMapper.selectAudioById(audioFile.getAudioId());
                return ReturnResult.success("上传成功", savedAudio);
            } else {
                // 删除已上传的文件
                if (destFile.exists()) {
                    destFile.delete();
                }
                return ReturnResult.error(500, "文件信息保存失败");
            }

        } catch (Exception e) {
            // 异常时也要删除已上传的文件
            if (destFile != null && destFile.exists()) {
                destFile.delete();
            }
            return ReturnResult.error(500, "文件上传失败: " + e.getMessage());
        }
    }

    @Override
    public ReturnResult<Boolean> updateAudioInfo(AudioFile audioFile) {
        try {
            if (audioFile.getAudioId() == null) {
                return ReturnResult.error(400, "文件ID不能为空");
            }

            // 检查文件是否存在
            if (audioFileMapper.checkAudioExists(audioFile.getAudioId()) == 0) {
                return ReturnResult.notFound();
            }

            int result = audioFileMapper.updateAudio(audioFile);
            return result > 0 ?
                    ReturnResult.success("更新成功", true) :
                    ReturnResult.error(500, "更新失败", false);
        } catch (Exception e) {
            return ReturnResult.error(500, "更新失败: " + e.getMessage(), false);
        }
    }

    @Override
    public ReturnResult<Boolean> deleteAudio(Integer audioId) {
        try {
            // 获取文件存储路径
            String storagePath = audioFileMapper.selectStoragePathById(audioId);
            if (storagePath == null) {
                return ReturnResult.notFound();
            }

            // 删除数据库记录
            int result = audioFileMapper.deleteAudio(audioId);
            if (result > 0) {
                // 删除物理文件
                File file = new File(uploadDir + File.separator + storagePath);
                if (file.exists()) {
                    file.delete();
                }
                return ReturnResult.success("删除成功", true);
            } else {
                return ReturnResult.error(500, "删除失败", false);
            }
        } catch (Exception e) {
            return ReturnResult.error(500, "删除失败: " + e.getMessage(), false);
        }
    }

    @Override
    public ReturnResult<String> playAudio(Integer audioId) {
        try {
            // 检查文件是否存在
            if (audioFileMapper.checkAudioExists(audioId) == 0) {
                return ReturnResult.notFound();
            }

            // 更新播放次数
            audioFileMapper.updatePlayCount(audioId);

            // 获取文件访问URL
            String storagePath = audioFileMapper.selectStoragePathById(audioId);
            String accessUrl = getFileAccessUrl(storagePath);

            return ReturnResult.success(accessUrl);
        } catch (Exception e) {
            return ReturnResult.error(500, "播放失败: " + e.getMessage());
        }
    }

    @Override
    public ReturnResult<String> downloadAudio(Integer audioId) {
        try {
            // 检查文件是否存在
            if (audioFileMapper.checkAudioExists(audioId) == 0) {
                return ReturnResult.notFound();
            }

            // 更新下载次数
            audioFileMapper.updateDownloadCount(audioId);

            // 获取文件访问URL
            String storagePath = audioFileMapper.selectStoragePathById(audioId);
            String accessUrl = getFileAccessUrl(storagePath);

            return ReturnResult.success(accessUrl);
        } catch (Exception e) {
            return ReturnResult.error(500, "下载失败: " + e.getMessage());
        }
    }

    @Override
    public String getFileAccessUrl(String storagePath) {
        return "/listening_manager/api/audio/file/" + storagePath.replace(File.separator, "/");
    }

    @Override
    public List<AudioFile> searchAudio(String keyword) {
        return audioFileMapper.searchByKeyword("%" + keyword + "%");
    }

    // 生成基于日期的存储路径
    private String generateStoragePath(String originalFilename) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String datePath = sdf.format(new Date());
        String filename = System.currentTimeMillis() + "_" + originalFilename;
        return datePath + File.separator + filename;
    }

    // 获取文件扩展名
    private String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf(".") == -1) {
            return "mp3";
        }
        return filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
    }
}
